﻿using log4net;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Text;
using System.Windows;
using Telerik.Windows.Controls;
using TruckScale.Helpers;
using TruckScale.Models;

namespace TruckScale.ViewModels
{
  public class ChangeDBConnectViewModel : ViewModelBase
  {
    public string Theme { get; set; } = Global._weighConfig["Theme"];
    public string MainFontSize { get; set; } = Global._weighConfig["MainFontSize"];
    public string InfoBar { get; set; }
    public string DataSource { get; set; }
    public string Port { get; set; }
    public string InitialCatalog { get; set; }
    public string UserId { get; set; }
    public string Password { get; set; }
    public DelegateCommand SaveCommand { get; private set; }
    public DelegateCommand RestartCommand { get; private set; }

    private Dictionary<string, string> cnnDictionary;

    public ChangeDBConnectViewModel()
    {
      string cnnstr = ConfigurationManager.ConnectionStrings["mysql"].ConnectionString;

      cnnDictionary = DBHelper.ParseConnectionString(cnnstr);

      DataSource = cnnDictionary["Data Source"];
      Port = cnnDictionary["port"];
      InitialCatalog = cnnDictionary["initial catalog"];
      UserId = cnnDictionary["userid"];
      Password = cnnDictionary["password"];

      SaveCommand = new DelegateCommand(OnSaveCommandExecuted, OnCanSaveExecuted);
      RestartCommand = new DelegateCommand((obj) => { Process.Start("TruckScale"); Application.Current.MainWindow.Close(); });
    }

    private bool OnCanSaveExecuted(object obj)
    {
      return true;
    }

    private void OnSaveCommandExecuted(object obj)
    {
      cnnDictionary["Data Source"] = DataSource.Replace("=", "").Replace(";", "");
      cnnDictionary["port"] = Port.Replace("=", "").Replace(";", "");
      cnnDictionary["initial catalog"] = InitialCatalog.Replace("=", "").Replace(";", "");
      cnnDictionary["userid"] = UserId.Replace("=", "").Replace(";", "");
      cnnDictionary["password"] = Password.Replace("=", "").Replace(";", "");

      string connectionString = DBHelper.BuildConnectionString(cnnDictionary);

      Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
      config.ConnectionStrings.ConnectionStrings["mysql"].ConnectionString = connectionString;
      config.Save(ConfigurationSaveMode.Modified);
      ConfigurationManager.RefreshSection("connectionStrings");

      var UserList = UserModel.SelectValidUser();

      if (UserList == null)
      {
        InfoBar = "数据库连接失败，请联系管理员！";
      }
      else
      {
        InfoBar = "数据库连接成功，请重启软件！";
      }
    }
  }
}
